import React from "react";
import { WeaDialog, WeaInput } from "ecCom";
import window from '../../util';
import { observer } from 'mobx-react';
import { Button, Modal, message } from "antd";
// import _ from "lodash";
import MapStore from '../../stores/card/MapStore';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import loadjs from 'loadjs';
export interface MapContainerProps {
    mapStore: MapStore;
    iconInfo?: any;
}

@observer
export default class MapContainer extends React.Component<MapContainerProps, any> {
    map: any;
    marker: any;
    toolBar: any;
    geolocation: any;
    scale: any;
    constructor(props) {
        super(props);
        this.state = {
            addressParams: ""
        }
    }
    componentDidMount() {
        if (!loadjs.isDefined('mapjs')) {
            loadjs(["https://webapi.amap.com/maps?v=1.4.4&key=53a92850ca00d7f77aef3297effd8d59"], 'mapjs', {
                //&plugin=AMap.Geocoder,AMap.ToolBar,AMap.Scale
                success: () => {
                    let value = this.props.mapStore.defaultAddress;
                    let { lnglat } = this.props.mapStore;
                    if (value == '') {
                        //value = getLabel(501929, '上海');
                    }
                    
                    this.paint(value, lnglat);
                }
            });
        } else {
            let value = this.props.mapStore.defaultAddress;
            let { lnglat } = this.props.mapStore;
            if (value == '') {
               // value = getLabel(501929, '上海');
            }
            this.paint(value, lnglat);
        }
    }

    paint = (title, lnglat: any = []) => {
        const that = this;
        if (window.AMap) {
            if (!this.map) {
                if (window.AMap.ToolBar && window.AMap.Scale) {
                    that.paintAfter(title, lnglat);
                } else {
                    window.AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
                        that.paintAfter(title, lnglat);
                    });
                }

            }
        } else {
            setTimeout(() => {
                that.paint(title, lnglat);
            }, 50);
        }
    }
    paintAfter = (title, lnglat: any = []) => {
        this.toolBar = new window.AMap.ToolBar({
            visible: true
        });
        this.scale = new window.AMap.Scale({
            visible: true
        });
        this.map = new window.AMap.Map(this.refs._map, {
            resizeEnable: true,
        });
        this.map.addControl(this.toolBar);   //添加工具条控制
        this.map.addControl(this.scale);
        this.toolBar.show();
        this.toolBar.showDirection();
        this.toolBar.showRuler();
        this.scale.show();
        this.map.on('click', (e) => {
            this.regeocoder([e.lnglat.getLng(), e.lnglat.getLat()])
        });

        if (title) {
            this.geocoder(title, lnglat);
        } else {
            this.geoCurrentLocation();
        }
    }
    geocoder = (title, lnglat: any = []) => {
        const that = this;
        if (window.AMap.Geocoder) {
            that.geocoderAfter(title, lnglat);
        } else {
            window.AMap.plugin(['AMap.Geocoder'], function () {
                that.geocoderAfter(title, lnglat);
            })
        }
    }

    geocoderAfter = (title, lnglat: any = []) => {
        const that = this;
        var geocoder = new window.AMap.Geocoder({
            radius: 1000 //范围，默认：500
        });
        //地理编码,返回地理编码结果
        if (lnglat.length > 0) {//如果有经纬度优先通过经纬度定位
            this.map.remove(this.marker || "");
            this.addMarker(0, lnglat, title);
            this.map.setFitView();
        } else {
            geocoder.getLocation(title, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    this.map.remove(this.marker || "");
                    this.geocoder_CallBack(result);
                } else {
                    Modal.info({
                        title: getLabel(15172, '系统提示'),
                        content: getLabel(128181, "未能定位具体位置！ 1.请确保所有字词拼写正确 2.尝试不同的关键字 3.尝试更宽泛的关键字"),
                        onOk() {
                            that.geoCurrentLocation();
                        },
                    })
                }
            });
        }

    }

    regeocoder = (lnglatXY) => {
        const that = this;
        if (window.AMap.Geocoder) {
            that.regeocoderAfter(lnglatXY);
        } else {
            window.AMap.plugin(['AMap.Geocoder'], function () {
                that.regeocoderAfter(lnglatXY);
            })
        }
    }
    regeocoderAfter = (lnglatXY) => {
        var geocoder = new window.AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        //已知地理坐标，逆地理编码   
        geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
                this.reGeocoder_CallBack(lnglatXY, result);
            }
        });
    }
    geocoder_CallBack = (data) => {
        //地理编码结果数组
        var geocode = data.geocodes;
        for (let i = 0; i < 1; i++) {
            const position = [geocode[i].location.getLng(), geocode[i].location.getLat()];
            this.addMarker(i, position, geocode[i].formattedAddress);
        }
        this.map.setFitView();
    }
    reGeocoder_CallBack = (lnglatXY, data) => {
        this.addMarker("e", lnglatXY, data.regeocode.formattedAddress);
    }

    addMarker = (_, p, address) => {
        if (this.marker) {
            this.map.remove(this.marker);
        }
        const that = this;
        if (window.AMap.Marker) {
            that.addMarkerAfter(_, p, address);
        } else {
            window.AMap.plugin(['AMap.Marker'], function () {
                that.addMarkerAfter(_, p, address);
            });
        }
    }
    addMarkerAfter = (_, p, address) => {
        this.marker = new window.AMap.Marker({
            map: this.map,
            position: p
        });
        let infoWindow = new window.AMap.InfoWindow({
            content: address,
            offset: { x: 0, y: -30 }
        });
        infoWindow.open(this.map, this.marker.getPosition());
        this.marker.on("mouseover", (_) => {
            infoWindow.open(this.map, this.marker.getPosition());
        });
        this.props.mapStore.updateAddress(address, p);
    }

    geoCurrentLocation = () => {
        window.AMap.plugin('AMap.Geolocation', () => {
            this.geolocation = new window.AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                buttonOffset: new window.AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                buttonPosition: 'RB'
            });
            this.map.addControl(this.geolocation);
            this.geolocation.getCurrentPosition();
            window.AMap.event.addListener(this.geolocation, 'complete', this.onComplete);//返回定位信息
            window.AMap.event.addListener(this.geolocation, 'error', this.onError);      //返回定位出错信息
        });
    }
    onComplete = (data) => {
        this.addMarker("e", [data.position.getLng(), data.position.getLat()], getLabel(34177, "当前位置") + `:${data.formattedAddress}`);
    }
    onError = () => {
        message.warning(getLabel(383751, "定位失败"))
    }
    searchAddress = () => {
        const { addressParams } = this.state;
        this.map = undefined;        //处理搜索不生效问题
        this.paint(addressParams);
    }
    render() {
        const { mapStore } = this.props;
        const { defaultAddress } = mapStore;
        return (
            <div style={{ height: '100%', }}>
                <div style={{ position: "absolute", top: 20, left: 70, zIndex: 1, whiteSpace: 'nowrap' }}>
                    <WeaInput defaultValue={defaultAddress} onChange={(v) => this.setState({ addressParams: v })} onPressEnter={() => { this.searchAddress() }} /><Button type="primary" onClick={this.searchAddress} style={{ margin: "0 0 3px 10px" }}>搜索</Button>
                </div>
                <div ref='_map' style={{ height: '100%' }}></div>
            </div>
        )
    }
}


@observer
export class MapAddressDialog extends React.Component<MapContainerProps, any> {
    render() {
        const { mapStore, iconInfo } = this.props;
        return (
            <WeaDialog
                onCancel={mapStore.onCancel}
                title={getLabel(126782, "获取地址")}
                visible={mapStore.visible}
                iconBgcolor={iconInfo.iconBg || "#96358a"}
                icon={iconInfo.icon || 'icon-coms-ModelingEngine'}
                iconFontColor={iconInfo.iconColor || "#fff"}
                style={{ width: 820, height: 520 }}
                hasScroll
                buttons={mapStore.showButtons ? [
                    (<Button type="primary" onClick={mapStore.getLocation}>{getLabel(383752, '获取位置')}</Button>),
                    (<Button type="primary" onClick={mapStore.getLocationCover}>{getLabel(126783, '获取并覆盖')}</Button>),
                    (<Button type="ghost" onClick={mapStore.onCancel}>{getLabel(309, "关闭")}</Button>)
                ] : []}
            >
                {mapStore.visible && <MapContainer ref="_map" mapStore={mapStore} />}
            </WeaDialog>
        )
    }
}